package fw.mvc.config;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.*;

import fw.mvc.annotation.*;

/**
 * key: String(request path); 
 * value: ConfigDoMap( do config infos).
 * @author feng xu on 20140919.
 *
 */
public class ConfigMap extends HashMap<String, ConfigDoMap> {
	
	private static ConfigMap instance = new ConfigMap(); 
	
	private ConfigMap(){
		
	}
	
	public static ConfigMap getInstance(){
		return instance;
	}
	
	public static void init(String packageName){
		List<String> classNames = PackageUtil.getClassNames(packageName);
		classNames.forEach(System.out::println);
		
		classNames.stream().forEach(className -> {
			try {
				Class cls = Class.forName(className);
				if(cls.isAnnotationPresent(Request.class)){
					Request reqAnno = (Request)cls.getAnnotation(Request.class);
					
					ConfigDoMap doConfig = new ConfigDoMap();
					doConfig.setPath(reqAnno.path());
					doConfig.setFormClass(reqAnno.form());
					doConfig.setActionClass(className);
					Result[] results = (Result[]) cls.getAnnotationsByType(Result.class);
					for(Result result : results){
						doConfig.put(result.condition(), result.renderer());
					}
					
					instance.put(doConfig.getPath(), doConfig);
				}
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});
	}
	
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		this.forEach((path, doMap) -> sb.append(doMap.toString()).append("\n"));
		return sb.toString();
	}
}
